package com.bdsy.system.aop;

import com.bdsy.common.utils.HttpContextUtils;
import com.bdsy.common.utils.IPUtils;
import com.bdsy.system.annotation.SysLog;
import com.bdsy.system.model.UserOperationLog;
import com.bdsy.system.service.UserOperationLogService;
import com.bdsy.system.shiro.ShiroUtils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class SysLogAspect {
	
	@Autowired
	private UserOperationLogService logService;
	
	@Pointcut("@annotation(com.bdsy.system.annotation.SysLog)") 
	public void logPointCut() { 
		
	}
	
	@Before("logPointCut()")
	public void saveSysLog(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		
		UserOperationLog sysLog = new UserOperationLog();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			sysLog.setOperation(syslog.value());
		}
		
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");
		
		/*Object[] args = joinPoint.getArgs();
		String params = JSON.toJSONString(args[0]);*/
		sysLog.setParams(null);
		
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		sysLog.setIp(IPUtils.getIpAddr(request));
		
		String username = ShiroUtils.getUser().getUserName();
		sysLog.setUsername(username);
		
		sysLog.setCreateDate(new Date());

		logService.save(sysLog);
	}
	
}
